/*
 * Create:      柿子
 * CreateDate:  2022/11/21
 * Describe：   视光 - 供应商维护
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, message, Tooltip, Popconfirm, Icon, Radio, Select, Checkbox, Badge, Spin } from 'antd';
import { Util, dayFormat } from 'tools';
import store from 'store';
import moment from 'moment';
import SelectFromBrandLibrary from './component/SelectFromBrandLibrary';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import ReturnOrder from '../glassesManagement/component/ReturnOrder';
import SupplierAuditRecord from './component/SupplierAuditRecord';
import RangeDatePicker from 'components/rangePicker/index';
import iconListVisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

class SupplierMaintenance extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      tabActive: '1',
      queryParams: {
        inputDesc: undefined,
        startDate: undefined,
        endDate: undefined,
        useFlag: true,
        status: '', // 审核状态
        statusType: undefined, // 审核类型
      },
      page: 1,
      pageSize: 20,
      loading: false,
      tableData: [],
      total: 0,
      totalWidth: 0,
      columns: [],
      rowID: '',
      rowData: {},
      copyRowData: {},
      formData: [],
      saveLoading: false,
      productLoading: false,
      productTableData: [],
      productTotalWidth: 900,
      productColumns: [],
      productRowID: '',
      userInfo: undefined, // 用户信息
      userLoading: false,
      userTableData: [],
      userTotalWidth: 450,
      userColumns: [],
      userRowID: '',
      userSelectData: [],
      modalFormData: [],
      modalRowData: {},
      queryHeight: 78, // 查询栏高度
      categoryData: {},
      licenceData: [], // 许可证数据 - 默认至少存在一个
      licenceFormData: [], // 许可证表单数据
      addressFormData: [], // 地址信息
      otherFormData: [], // 其他信息
      tabList: [{
        key: '1',
        tab: '基本信息',
      }, {
        key: '2',
        tab: '首营产品目录',
      }],
      detailLoading: false,
      changeFlag: true,
      productName: undefined,
      filterProductName: ''
    };
    this.staticProductColumns = [{
      key: 1,
      title: '产品编码',
      dataIndex: 'stockCode',
      align: 'center',
      width: 100
    }, {
      key: 2,
      title: '产品名称',
      dataIndex: 'stockDesc',
      align: 'center',
      width: 250
    }, {
      key: 3,
      title: '品牌',
      dataIndex: 'brandDesc',
      align: 'center',
      width: 100
    }, {
      key: 4,
      title: '规格型号',
      dataIndex: 'varietyDesc',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '批准文号前缀',
      dataIndex: 'appPrefixDesc',
      align: 'center',
      width: 150
    }, {
      key: 6,
      title: '批准文号',
      dataIndex: 'apprNo',
      align: 'center',
      width: 100
    }, {
      key: 7,
      title: '注册证号',
      dataIndex: 'regCertNo',
      align: 'center',
      width: 100
    }];
    this.queryRef = React.createRef();
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('SupplierMaintenance', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('SupplierMaintenance', false);
      }
    }
    // 界面类型 - create(制单) / reviewed(审核)
    let categoryData = Util.getObjByUrlStr(newCategory);
    if (categoryData?.interfaceType === 'create') {
      let userTab = {
        key: '3',
        tab: '供应商用户'
      };
      this.state.tabList = [...this.state.tabList, userTab];
    }
    console.log('SupplierMaintenance', categoryData);
    this.setState({ categoryData }, () => {
      this.getTableColumns();
      this.getProductTableColumns();
      this.getAddressTableColumns();
      this.getOtherTableColumns();
      this.getLicenceTableColumns('init');
    });
  }

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  getSelectData = async () => {
    try {
      let { categoryData, queryParams } = this.state;
      let data = {
        params: [{
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
          // 首营产品目录为Y，医院用的供应商维护默认不传
          supplierFlag: categoryData?.supplierFlag || 'N'
        }]
      }
      let res = await React.$asyncPost(this, '17060026', data);
      let selectData = res?.result || {};
      let status = selectData?.status || [];
      let activeStatusArr = status && status.filter(item => item.default === 'Y');
      queryParams.status = activeStatusArr && activeStatusArr.length > 0 ? activeStatusArr[0]?.id : ''; // 默认审核状态
      if (categoryData?.interfaceType === 'reviewed') { // 默认状态类型
        let statusType = selectData?.statusType || [];
        let activeStatusTypeArr = statusType && statusType.filter(item => item.default === 'Y');
        queryParams.statusType = activeStatusTypeArr && activeStatusTypeArr.length > 0 ? activeStatusTypeArr[0]?.id : '';
        // 默认日期
        queryParams.startDate = selectData?.startDate || moment().format(dayFormat);
        queryParams.endDate = selectData?.endDate || moment().format(dayFormat);
      }
      this.setState({ selectData, queryParams }, () => {
        this.getTableData();
        this.setState({ queryHeight: this.queryRef?.current?.clientHeight || 78 });
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      let data = {
        params: [{
          compontName: categoryData?.interfaceType === 'reviewed' ? 'SupplierMaintenanceAudit' : 'SupplierMaintenance',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      let formData = res.result?.formData || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              if ((item.dataIndex === 'statusDesc' && text === '停用') || (item.dataIndex === 'auditStatusDesc' && (text === '审核拒绝' || text === '拒绝审核' || text === '拒绝'))) { // 状态
                return (
                  <span className="common-record-delete-span">{text}</span>
                );
              } else {
                return text;
              }
            }
          }
        })
        this.setState({
          columns,
          totalWidth: res.totalWidth
        });
      }
      this.setState({ formData });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取表头数据
  getLicenceTableColumns = async (type) => {
    try {
      let data = {
        params: [{
          compontName: 'SupplierMaintenanceLicence',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let licenceFormData = res.result?.formData || [];
      this.setState({ licenceFormData }, () => {
        if (type === 'init') {
          this.getSelectData();
          this.handleLicenceAdd();
        }
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取表头数据
  getAddressTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SupplierMaintenanceAddress',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let addressFormData = res.result?.formData || [];
      this.setState({ addressFormData });
    } catch (error) {
      console.log(error);
    }
  }

  // 获取表头数据
  getOtherTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SupplierMaintenanceOther',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let otherFormData = res.result?.formData || [];
      this.setState({ otherFormData });
    } catch (error) {
      console.log(error);
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 获取列表数据
  getTableData = async (isReset) => {
    try {
      this.setState({ loading: true });
      const { queryParams, page, pageSize, categoryData } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag && categoryData?.interfaceType === 'create' ? 'Y' : 'N',
        }],
        pagination: [{
          pageSize,
          currentPage: page,
        }],
      }
      let res = await React.$asyncPost(this, '17060085', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ tableData, total: res.result?.total || 0, loading: false }, () => {
        isReset !== 'N' && this.handleReset();
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false }, () => {
        isReset !== 'N' && this.handleReset();
      });
    }
  }

  // 操作行
  handleRowClick = (record) => {
    const { categoryData } = this.state;
    const idIndex = categoryData?.idIndex || 'vendorID';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[idIndex]))) {
          this.setState({ rowID: record[idIndex] }, () => {
            let { tabActive } = this.state;
            this.queryRowDataByID();
            if (tabActive === '3') { // 供应商用户
              this.getUserTableData();
            }
          });
        } else {
          this.handleReset();
        }
      }
    }
  }

  // 根据行ID获取明细数据
  queryRowDataByID = async () => {
    try {
      this.setState({ detailLoading: true });
      const { categoryData, rowID, selectData } = this.state;
      const idIndex = categoryData?.idIndex || 'vendorID';
      let data = {
        params: [{
          [idIndex]: rowID,
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
        }]
      }
      let res = await React.$asyncPost(this, '17060086', data);
      let rowData = res?.result || {};
      let copyRowData = JSON.parse(JSON.stringify(rowData));
      let productTableData = Util.addKeyValueToDataSource(res.result?.productArr || []);
      let licenceData = [];
      let licenceArr = this.getLicenceArr(rowData);
      if (licenceArr && licenceArr.length > 0) { // 不存在则默认返回一个
        for (let i = 0; i < licenceArr.length; i++) {
          let currentKey = i + 1;
          let currentFormData = this.filterLicenceFormData(currentKey, licenceArr[i]?.newLicenceTypeID || licenceArr[i]?.licenceTypeID || '');
          let currentLicenceRowData = this.filterLicenceValues(licenceArr[i], 'add', currentKey)
          licenceData.push({
            key: currentKey,
            licenceID: licenceArr[i]?.licenceID || '',
            deleteFlag: licenceArr[i]?.deleteFlag || '',
            rowData: currentLicenceRowData, // 可不存
            title: licenceArr[i]?.licenceTypeDesc || '许可证',
            formData: currentFormData
          });
          rowData = { ...rowData, ...currentLicenceRowData }
          this.state['licenceFormData' + currentKey] = currentFormData;
        }
      } else {
        let defaultFormData = this.filterLicenceFormData(1);
        licenceData = [{
          key: 1,
          formData: defaultFormData
        }];
        this.state['licenceFormData' + 1] = [...defaultFormData];
      }
      let updateObj = rowData?.updateObj?.modifyJson || {};
      let currentUpdateObj = {}; // 实际修改的数据
      // 提交修改和退回提交展示痕迹|已经审核界面完成审核需展示痕迹
      if (typeof (updateObj) === 'object' && JSON.stringify(updateObj) !== '{}' && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
        let diffData = [], oldData = {}, newData = {};
        for (let keys in updateObj) {
          for (let rowKeys in rowData) {
            if (keys === rowKeys && String(updateObj[keys]) !== String(rowData[rowKeys])) {
              currentUpdateObj[keys] = updateObj[keys]
              let formDataDataIndex = this.getTheCorrespondingFromData(keys, licenceData);
              let formItemData = Util.returnDataCccordingToAttributes(this.state[formDataDataIndex], keys, 'dataIndex');
              let selectDataKey = formItemData?.className;
              let typeCode = formItemData?.typeCode;
              let title = typeCode === 'RangePicker' ? (formItemData?.dataIndex.indexOf(keys) === 0 ? (formItemData?.title + '【开始】') : (formItemData?.title + '【结束】')) : formItemData?.title;
              let newVal = typeCode === 'Select' && updateObj[keys] && selectData[selectDataKey] ? Util.returnDataCccordingToAttributes(selectData[selectDataKey], updateObj[keys], 'id').descripts : updateObj[keys];
              let oldVal = typeCode === 'Select' && rowData[rowKeys] && selectData[selectDataKey] ? Util.returnDataCccordingToAttributes(selectData[selectDataKey], rowData[rowKeys], 'id').descripts : rowData[rowKeys];
              newData[keys] = newVal;
              oldData[keys] = oldVal;
              diffData.push({
                typeCode,
                id: 'linkID_' + (typeCode === 'RangePicker' ? formItemData?.dataIndex : keys),
                dataIndex: keys,
                title,
                new: newVal,
                old: oldVal
              })
            }
          }
        }
        rowData = { ...rowData, ...updateObj }; // 界面展示修改后的值
        rowData.diffData = diffData;
      }
      this.setState({
        licenceData,
        rowData,
        copyRowData,
        productTableData,
        detailLoading: false,
        filterProductName: '',
        productName: undefined
      }, () => {
        this.setColumnsLinkUrl('formData', currentUpdateObj);
        this.setColumnsLinkUrl('addressFormData', currentUpdateObj);
        this.setColumnsLinkUrl('otherFormData', currentUpdateObj);
        for (let i = 0; i < licenceData.length; i++) {
          let currentKey = i + 1;
          if (licenceData[i]?.deleteFlag !== 'Y') {
            this.setColumnsLinkUrl(('licenceFormData' + licenceData[i].key), currentUpdateObj);
          }
          setTimeout(() => {
            this['licenceRef' + currentKey] && this['licenceRef' + currentKey]?.handleDataTransformation();
          }, 100)
        }
      });
    } catch (error) {
      this.setState({ detailLoading: false });
    }
  }

  // 获取界面展示的许可证信息
  getLicenceArr = (rowData) => {
    const { categoryData } = this.state;
    let oldLicenceArr = rowData?.licenceArr || [];
    if (rowData.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
      let newLicenceArr = JSON.parse(JSON.stringify(rowData?.updateObj?.licenceArr || []));
      for (let i = 0; i < newLicenceArr.length; i++) {
        for (let j = 0; j < oldLicenceArr.length; j++) {
          if (newLicenceArr[i] && 'licenceID' in newLicenceArr[i] && oldLicenceArr[j] && 'licenceID' in oldLicenceArr[j] && (newLicenceArr[i].licenceID === oldLicenceArr[j].licenceID)) {
            newLicenceArr[i] = { ...newLicenceArr[i], ...oldLicenceArr[j], newLicenceTypeID: newLicenceArr[i]?.licenceTypeID || oldLicenceArr[j]?.licenceTypeID || '' }
          }
        }
      }
      return newLicenceArr;
    }
    return oldLicenceArr;
  }

  // 根据dataIndex获取对应的表头数据
  getTheCorrespondingFromData = (dataIndex, licenceData) => {
    let { formData, otherFormData, addressFormData } = this.state;
    let formFlag = '';
    for (var i = 0; i < formData.length; i++) {
      if ((formData[i].dataIndex === dataIndex) || (formData[i].dataIndex.indexOf('^') > -1 && formData[i].dataIndex.indexOf(dataIndex) > -1)) {
        formFlag = 'formData';
        break;
      }
    }
    if (!formFlag) { // formFlag不存在时再去currentLicenceFormData中查找
      for (let i = 0; i < licenceData.length; i++) {
        let currentLicenceFormData = licenceData[i]?.formData || [];
        for (let j = 0; j < currentLicenceFormData.length; j++) {
          if ((currentLicenceFormData[j].dataIndex === dataIndex) || (currentLicenceFormData[j].dataIndex.indexOf('^') > -1 && currentLicenceFormData[j].dataIndex.indexOf(dataIndex) > -1)) {
            formFlag = 'licenceFormData' + (licenceData[i]?.key || (i + 1));
            break
          }
        }
      }
    }
    if (!formFlag) { // formFlag不存在时再去addressFormData中查找
      for (var i = 0; i < addressFormData.length; i++) {
        if ((addressFormData[i].dataIndex === dataIndex) || (addressFormData[i].dataIndex.indexOf('^') > -1 && addressFormData[i].dataIndex.indexOf(dataIndex) > -1)) {
          formFlag = 'addressFormData';
          break;
        }
      }
    }
    if (!formFlag) { // formFlag不存在时再去otherFormData中查找
      for (var i = 0; i < otherFormData.length; i++) {
        if ((otherFormData[i].dataIndex === dataIndex) || (otherFormData[i].dataIndex.indexOf('^') > -1 && otherFormData[i].dataIndex.indexOf(dataIndex) > -1)) {
          formFlag = 'otherFormData';
          break;
        }
      }
    }
    return formFlag;
  }

  setColumnsLinkUrl = (cloumnsIndex, updateObj) => {
    const { rowData, categoryData } = this.state;
    for (let i = 0; i < this.state[cloumnsIndex].length; i++) {
      let currentColumnsRecord = this.state[cloumnsIndex][i];
      this.state[cloumnsIndex][i].linkUrl = '';
      for (let updateKey in updateObj) {
        if (((currentColumnsRecord.dataIndex === updateKey) || (currentColumnsRecord?.typeCode === 'RangePicker' && (currentColumnsRecord.dataIndex.indexOf(updateKey) > -1))) && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
          this.state[cloumnsIndex][i].linkUrl = 'linkID_' + (currentColumnsRecord?.typeCode === 'RangePicker' ? currentColumnsRecord.dataIndex : updateKey);
          break;
        }
      }
    }
    this.setState({});
  }

  // 处理许可证表单数据
  filterLicenceFormData = (key = 1, licenceTypeID) => {
    let { licenceFormData, selectData } = this.state;
    let nLicenceFormData = Util.customDeepCopy(licenceFormData);
    for (let i = 0; i < nLicenceFormData.length; i++) {
      let currentDataIndex = nLicenceFormData[i].dataIndex;
      nLicenceFormData[i].dataIndex = currentDataIndex + '_' + key;
      if (currentDataIndex === 'licenceScope') { // 修改范围描述
        nLicenceFormData[i].title = +licenceTypeID === 1 ? '经营范围' : (+licenceTypeID === 5 ? '诊疗科目' : '生产范围');
      }
      if (currentDataIndex === 'licenceNo') {
        nLicenceFormData[i].title = +licenceTypeID === 5 ? '登记号' : '许可证编码';
      }
      if (currentDataIndex === 'endDate') { // 有效期至
        nLicenceFormData[i].title = +licenceTypeID === 5 ? '有效期限' : '有效期至';
        nLicenceFormData[i].typeCode = +licenceTypeID === 5 ? 'RangePicker' : 'Date';
        nLicenceFormData[i].dataIndex = +licenceTypeID === 5 ? ('stDate_' + key + '^endDate_' + key) : ('endDate_' + key);
      }
      if (currentDataIndex === 'licenceTypeID') { // 许可证类型
        // nLicenceFormData[i].defaultValue = '1';
        nLicenceFormData[i].detailItem = selectData?.licenceType || [];
        nLicenceFormData[i].callBackResult = 'Fn' + key;
        nLicenceFormData[i].changeCallBack = this.handleLicenceTypeChange;
      }
    }
    return nLicenceFormData;
  }

  // 选中行操作
  handleRowClassName = (record) => {
    const { categoryData } = this.state;
    const idIndex = categoryData?.idIndex || 'vendorID';
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  // tabs切换
  handleTabsChange = key => {
    let { userColumns, rowID } = this.state;
    if (!rowID) {
      message.error('请先选中左侧供应商列表后切换！')
      return
    };
    this.setState({ tabActive: key }, () => {
      if (this.state.tabActive === '3') { // 供应商用户
        this.getUserTableData();
        if (!(userColumns && userColumns.length > 0)) {
          this.getUserTableColumns();
        }
      }
    });
  }

  // 保存
  handleSave = Util.debounce(async (fn, statusCode) => {
    let { licenceData, rowID, rowData } = this.state;
    let baseInfoVal = await this.baseInfoRef.handleSave();
    if (baseInfoVal && baseInfoVal.error) {
      message.error(baseInfoVal?.errorMessage || '请先完善基本信息。');
      return;
    }
    let licenceArr = [];
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        let currentKey = i + 1;
        let licenceVal = await this['licenceRef' + currentKey].handleSave();
        if (licenceVal && licenceVal.error) {
          message.error('请先完善许可证相关信息。');
          return;
        } else {
          let currentLicenceID = 'licenceID_' + currentKey;
          licenceArr.push({ ...this.filterLicenceValues({ ...licenceVal, licenceID: rowData && currentLicenceID in rowData && rowData[currentLicenceID] ? rowData[currentLicenceID] : '' }) });
        }
      } else { // 删除的传入原值
        licenceArr.push({ ...this.filterLicenceValues(licenceData[i]?.rowData || {}), deleteFlag: 'Y' });
      }
    }
    let addressVal = await this.addressRef.handleSave();
    if (addressVal && addressVal.error) {
      message.error('请先完善其他信息。');
      return;
    }
    let otherVal = await this.otherRef.handleSave();
    if (otherVal && otherVal.error) {
      message.error('请先完善其他信息。');
      return;
    }
    fn && fn(statusCode, {
      ...baseInfoVal,
      ...addressVal,
      ...otherVal,
      vendorID: rowID,
      licenceArr,
      baseArr: this.getBaseArr(),
    })
  })

  // 处理许可证数据
  filterLicenceValues = (licenceVal, type, key) => {
    let nLicenceVal = {};
    for (let keys in licenceVal) {
      if (type === 'add') {
        nLicenceVal[keys + '_' + key] = licenceVal[keys];
      } else {
        let currentKey = keys.indexOf('_') > -1 ? keys.split('_')[0] : keys;
        nLicenceVal[currentKey] = licenceVal[keys];
      }
    }
    return nLicenceVal;
  }

  // 基本信息保存 
  handleBaseInfoSave = async (statusCode, baseObj) => {
    try {
      this.setState({ saveLoading: true });
      let data = {
        params: [{
          status: statusCode,
          baseObj,
          productArr: this.getProductArr(),
        }]
      }
      let res = await React.$asyncPost(this, '17060087', data);
      message.success(res.errorMessage || '保存成功');
      this.setState({ saveLoading: false });
      this.getTableData();
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  }

  // 判断表单信息是否修改
  isModifyForm = (returnType = '') => {
    let { rowData, licenceData } = this.state;
    let baseValues = this.baseInfoRef && this.baseInfoRef.getFieldsValue('N');
    let licenceValues = {};
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        let currentKey = i + 1;
        let currentLicenceVal = (this['licenceRef' + currentKey] && this['licenceRef' + currentKey].getFieldsValue('N')) || {};
        licenceValues = { ...licenceValues, ...currentLicenceVal };
      }
    }
    let addressValues = this.addressRef && this.addressRef.getFieldsValue('N');
    let otherValues = this.otherRef && this.otherRef.getFieldsValue('N');
    let values = { ...baseValues, ...licenceValues, ...addressValues, ...otherValues };
    let isModify = Util.isModifyForm(values, rowData, returnType);
    return isModify;
  }

  // 处理首营产品目录数据 - 必须传: I - 新增; D - 删除; N - 无变化 
  getProductArr = () => {
    let { productTableData } = this.state;
    for (let i = 0; i < productTableData.length; i++) {
      if (productTableData[i].productStatus !== 'D') { // 必须传: I - 新增; D - 删除; N - 无变化 
        productTableData[i].productStatus = productTableData[i].vendorLinkProductID ? 'N' : 'I';
      }
    }
    return productTableData;
  }

  // 修改库存项状态 - 拒绝时传入25，审核通过传入30
  handleModifyDataStatus = async (statusCode, baseObj = {}, compnentSource, remark) => {
    try {
      this.setState({ saveLoading: true });
      const { rowData, categoryData } = this.state;
      let modifyJson = {};
      if (categoryData?.interfaceType === 'create' && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '10' || rowData?.modifyStatus === '25' || rowData?.modifyStatus === '30')) {
        let modifyForm = this.isModifyForm('obj');
        let oldModifyJson = rowData?.updateObj?.modifyJson || {};
        // 退回的时候需和历史修改的数据一并保存
        modifyJson = rowData?.modifyStatus === '25' ? { ...oldModifyJson, ...modifyForm } : { ...modifyForm }
      }
      let data = {
        params: [{
          vendorID: rowData?.vendorID || '',
          type: rowData?.auditStatus !== '30' ? 'INSERT' : 'UPDATE', // INSERT-新增时 / UPDATE-修改
          status: statusCode,
          remark: remark || undefined, // 拒绝备注
          updateValue: categoryData?.interfaceType === 'create' ? {
            ...baseObj,
            ...modifyJson,
            modifyJson, // 需要修改的数据 - 提交修改时传入
          } : {},
          productArr: this.getProductArr(), // 首营产品目录
        }]
      }
      let res = await React.$asyncPost(this, '17060088', data);
      message.success(res?.errorMessage || '操作成功');
      this.setState({ saveLoading: false });
      this.returnOrderRef && this.returnOrderRef.modifyVisible(false, '', '', 'Y');
      this.getTableData('Y');
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  }

  getBaseArr = () => {
    const { rowData, formData, licenceData, otherFormData, addressFormData } = this.state;
    let baseValues = this.baseInfoRef && this.baseInfoRef.getFieldsValue('N');
    let baseDiffData = Util.getDiffData(baseValues, rowData, formData);
    let addressValues = this.addressRef && this.addressRef.getFieldsValue('N');
    let addressDiffData = Util.getDiffData(addressValues, rowData, addressFormData);
    let otherValues = this.otherRef && this.otherRef.getFieldsValue('N');
    let otherDiffData = Util.getDiffData(otherValues, rowData, otherFormData);
    let licenceDiffData = [];
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        let currentKey = i + 1;
        let currentLicenceVal = this['licenceRef' + currentKey] && this['licenceRef' + currentKey].getFieldsValue('N') || {};
        let currentLicenceDiffData = Util.getDiffData(currentLicenceVal, rowData, licenceData[i]?.formData);
        licenceDiffData = [...licenceDiffData, ...currentLicenceDiffData];
      }
    }
    return [...baseDiffData, ...licenceDiffData, ...addressDiffData, ...otherDiffData];
  }

  // 基本信息重置
  handleReset = () => {
    let { licenceData } = this.state;
    for (let i = 0; i < licenceData.length; i++) {
      if (licenceData[i]?.deleteFlag !== 'Y') {
        this.setColumnsLinkUrl(('licenceFormData' + licenceData[i].key), {});
      }
    }
    this.setColumnsLinkUrl('formData', {});
    this.setColumnsLinkUrl('addressFormData', {});
    this.setColumnsLinkUrl('otherFormData', {});
    this.baseInfoRef && this.baseInfoRef.resetFields();
    this.addressRef && this.addressRef.resetFields();
    this.otherRef && this.otherRef.resetFields();
    this.setState({ tabActive: '1', rowID: '', rowData: {}, licenceData: [], productTableData: [], filterProductName: '', productName: undefined }, () => {
      this.handleLicenceAdd();
    });
  }

  // 录入顺序
  handleEntrySequence = (componentName) => {
    this.baseInfoRef && this.baseInfoRef.showFromMaintenanceModal(componentName);
  }

  // 新增产品
  handleProductAdd = () => {
    const { rowID, selectData, productColumns, productTotalWidth } = this.state;
    let columns = productColumns && productColumns.length > 0 ? productColumns : this.staticProductColumns;
    this.brandLibraryRef && this.brandLibraryRef.modifyVisible(true, rowID, selectData, columns, productTotalWidth);
  }

  // 获取首营产品目录表头数据
  getProductTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SelectFromBrandLibrary',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        columns = columns.map(item => {
          return {
            ...item,
            render: (text, record) => {
              return (
                <Tooltip title={text}>
                  <span className='ellipsis' style={{ width: '100%', display: 'block' }}>
                    {text}
                  </span>
                </Tooltip>
              )
            }
          }
        })
        this.setState({ productColumns: columns, productTotalWidth: res.totalWidth })
      }
      let modalFormData = res.result?.formData || [];
      this.setState({ modalFormData });
    } catch (error) {
      console.log(error);
    }
  }

  // 选中行操作
  handleProductRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.productRowID === '' || (this.state.productRowID && (this.state.productRowID !== record.stockID))) {
          this.setState({ productRowID: record.stockID });
        } else {
          this.setState({ productRowID: '' });
        }
      },
      // 暂不支持在此修改产品信息
      // onDoubleClick: () => {
      //   this.setState({ modalRowData: record }, () => {
      //     this.modalRef && this.modalRef.modifyVisible(true);
      //   })
      // }
    }
  }

  handleProductRowClassName = (record) => {
    return record.stockID === this.state.productRowID ? 'clickRowStyle' : (record?.productStatus === 'I' ? 'optometry-add-row-color' : (record?.productStatus === 'D' ? 'optometry-delete-row-color' : ''));
  }

  // 关联产品删除
  handleProductDelete = async (record, index, e, isRevert) => {
    try {
      React.$stopPropagation(e);
      let { productTableData } = this.state;
      if (record?.vendorLinkProductID) { // 保存过的直接置状态
        productTableData[index].productStatus = isRevert === 'revert' ? '' : 'D';
      } else {
        productTableData = productTableData.filter(item => item.stockID !== record?.stockID);
      }
      this.setState({ productTableData, productRowID: '' }, () => {
        message.success(isRevert === 'revert' ? '还原成功' : '删除成功');
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 获取用户表头数据
  getUserTableColumns = async () => {
    let columns = [];
    let totalWidth = 450;
    try {
      let data = {
        params: [{
          compontName: 'SupplierMaintenanceUser',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      columns = res.result?.C || [];
      totalWidth = res.totalWidth;
    } catch (error) {
      columns = [{
        key: 1,
        title: '用户名',
        dataIndex: 'userCode',
        align: 'center',
        width: 250
      }, {
        key: 2,
        title: '工号',
        dataIndex: 'userCode',
        align: 'center',
        width: 100
      }, {
        key: 3,
        title: '姓名',
        dataIndex: 'userName',
        align: 'center',
        width: 100
      }];
    }
    columns = columns.map((item, index) => {
      return {
        ...item,
        render: (text, record, childIndex) => {
          if (item.dataIndex === 'userDesc' && !(record && record.vendorLinkUserID)) {
            return (
              <Select
                showSearch
                showArrow={false}
                filterOption={false}
                notFoundContent={null}
                defaultActiveFirstOption={false}
                style={{ width: '90%' }}
                placeholder="输入用户名/工号/姓名回车查询"
                allowClear={record.loading === 'Y' || record.loading === true ? false : true} // 与loading效果互斥
                loading={record.loading === 'Y' || record.loading === true ? true : false}
                onSearch={() => { }}
                onInputKeyDown={(e) => this.handleSelecttKeyDown(e, childIndex)}
                value={record?.userID || undefined}
                onChange={(e) => this.handleUserChange(e, childIndex, record?.selectData || [])}
              >
                {React.$SelectOptions(record?.selectData || [], 'userID', 'userDesc',)}
              </Select>
            )
          } else {
            return (
              <Tooltip title={text}>
                <span className='ellipsis' style={{ width: '100%', display: 'block' }}>
                  {text}
                </span>
              </Tooltip>
            )
          }
        }
      }
    })
    this.setState({ userColumns: columns, userTotalWidth: totalWidth });
  }

  // 用户选择
  handleUserChange = (e, index, selectData) => {
    let currentData = Util.returnDataCccordingToAttributes(selectData, e, 'userID');
    this.state.userTableData[index] = {
      ...this.state.userTableData[index],
      ...currentData
    };
    this.setState({});
  }

  // 搜索框键盘事件
  handleSelecttKeyDown = async (e, index) => {
    if (+e.keyCode === 13) {
      this.getUserTableData('select', e.target.value, index);
    }
  }

  getUserTableData = async (type, userVal, index) => {
    try {
      const { rowID, userInfo } = this.state;
      if (!rowID) return;
      if (type === 'select') {
        this.state.userTableData[index].loading = true;
        this.setState({});
      } else {
        this.setState({ userLoading: true });
      }
      let data = {
        params: [{
          vendorID: rowID,
          linkFlag: type === 'select' ? 'N' : 'Y',
          inputDesc: type === 'select' ? userVal : userInfo,
        }]
      }
      let res = await React.$asyncPost(this, '17060030', data);
      let userTableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      if (type === 'select') { // 获取用户下拉数据
        this.state.userTableData[index].selectData = userTableData;
        this.state.userTableData[index].loading = false;
        this.setState({});
      } else {
        this.setState({ userTableData, userLoading: false, userRowID: '' });
      }
    } catch (error) {
      if (type === 'select') {
        this.state.userColumns[index].userSelectData = [];
        this.state.userColumns[index].loading = false;
        this.setState({});
      } else {
        this.setState({ userTableData: [], userLoading: false, userRowID: '' });
      }
    }
  }

  handleUserRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.userRowID === '' || (this.state.userRowID && (this.state.userRowID !== record.vendorLinkUserID))) {
          this.setState({ userRowID: record.vendorLinkUserID });
        } else {
          this.setState({ userRowID: '' });
        }
      }
    }
  }

  handleUserRowClassName = (record) => {
    return record.vendorLinkUserID === this.state.userRowID ? 'clickRowStyle' : '';
  }

  // 添加用户
  handleUserAdd = () => {
    let { userTableData } = this.state;
    let isAdd = true;
    for (var i = 0; i < userTableData.length; i++) {
      if (!(userTableData[i] && userTableData[i].vendorLinkUserID)) {
        isAdd = false;
        break;
      }
    }
    if (isAdd) {
      let addObj = {
        key: userTableData && userTableData.length > 0 ? (userTableData.length + 1) : 1
      };
      this.setState({ userTableData: [...userTableData, addObj] });
    } else {
      message.warning('为防止添加的数据丢失，请先保存未保存的数据')
    }
  }

  // 删除关联用户
  handleUserDelete = async record => {
    try {
      let data = {
        params: [{
          vendorLinkUserID: record?.vendorLinkUserID || ''
        }],
      }
      let res = await React.$asyncPost(this, '17060032', data);
      message.success(res.errorMessage || '删除成功');
      this.getUserTableData();
    } catch (error) {
      console.log(error)
    }
  }

  // 保存用户
  handleSaveUser = async record => {
    try {
      const { rowID } = this.state;
      let data = {
        params: [{
          vendorID: rowID,
          userID: record?.userID || ''
        }],
      }
      let res = await React.$asyncPost(this, '17060031', data);
      message.success(res.errorMessage || '保存成功');
      this.getUserTableData();
    } catch (error) {
      console.log(error)
    }
  }

  recordFormInput = record => {
    this.setState({ modalRowData: { ...this.state.modalRowData, ...record } })
  }

  handleModalSave = async values => {
    try {
      let { modalRowData } = this.state;
      let data = {
        params: [{
          ...values,
          stockID: modalRowData?.stockID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17060070', data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.modalRef && this.modalRef.modifyVisible(false, 'Y');
      this.setState({ modalRowData: {} }, () => {
        this.queryRowDataByID();
      });
    } catch (error) {
      this.setState({ productTableData: [] })
    }
  }

  // 退回
  handleReturn = () => {
    this.returnOrderRef && this.returnOrderRef.modifyVisible(true, {}, '25');
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'vendorID' || dataIndex === 'statusType' || dataIndex === 'status' || dataIndex === 'useFlag') {
        this.handleQuery();
      }
    })
  }

  // 查看审核记录
  handleAuditRecord = (record, e) => {
    React.$stopPropagation(e);
    this.auditRecordRef && this.auditRecordRef.modifyVisible(true, record);
  }

  // 新增许可证
  handleLicenceAdd = () => {
    let { licenceData } = this.state;
    let key = licenceData && licenceData.length > 0 ? licenceData.length + 1 : 1;
    let formData = this.filterLicenceFormData(key);
    this.state['licenceFormData' + key] = [...formData];
    licenceData.push({ key, formData });
    this.setState({ licenceData });
  }

  // 许可证类型切换
  handleLicenceTypeChange = (e, dataIndex, record) => {
    let { licenceData } = this.state;
    let callBackResult = (record?.callBackResult || 'Fn1').replace('Fn', '');
    let currentIndex = callBackResult - 1;
    if (licenceData && licenceData.length > currentIndex) {
      licenceData[currentIndex].title = record['licenceTypeDesc_' + callBackResult] || '';
      let currentFormData = licenceData[currentIndex]?.formData || [];
      // 修改范围描述
      for (let i = 0; i < currentFormData.length; i++) {
        if (currentFormData[i].code === 'licenceScope') { // 生产范围
          licenceData[currentIndex].formData[i].title = +record['licenceTypeID_' + callBackResult] === 1 ? '经营范围' : +record['licenceTypeID_' + callBackResult] === 5 ? '诊疗科目' : '生产范围';
        }
        if (currentFormData[i].code === 'licenceNo') { // 许可证编号
          licenceData[currentIndex].formData[i].title = +record['licenceTypeID_' + callBackResult] === 5 ? '登记号' : '许可证编码';
        }
        if (currentFormData[i].code === 'endDate') { // 有效期至
          licenceData[currentIndex].formData[i].title = +record['licenceTypeID_' + callBackResult] === 5 ? '有效期限' : '有效期至';
          licenceData[currentIndex].formData[i].typeCode = +record['licenceTypeID_' + callBackResult] === 5 ? 'RangePicker' : 'Date';
          licenceData[currentIndex].formData[i].dataIndex = +record['licenceTypeID_' + callBackResult] === 5 ? ('stDate_' + callBackResult + '^endDate_' + callBackResult) : ('endDate_' + callBackResult);
        }
      }
    }
    this.setState({ licenceData }, () => {
      this['licenceRef' + callBackResult] && this['licenceRef' + callBackResult].setFieldsValue({ [dataIndex]: record[dataIndex] }); // 解决第一次赋值异常
    });
  }

  // 删除许可证
  handleLicenceDelete = (index, record, isRevert) => {
    let { licenceData } = this.state;
    if (record && record.licenceID) {
      licenceData[index].deleteFlag = isRevert === 'revert' ? '' : 'Y';
    } else {
      licenceData = licenceData.filter(item => item.key !== record.key);
    }
    this.setState({ licenceData });
  }

  // 添加首营目录数据
  handleAddProductData = (productData) => {
    let { productTableData } = this.state;
    this.setState({ productTableData: [...productTableData, ...productData] });
  }

  filteProductTableData = () => {
    const { changeFlag, filterProductName, rowData } = this.state;
    let tableData = JSON.parse(JSON.stringify(this.state.productTableData));
    if (changeFlag && (rowData?.auditStatus === '20' || rowData?.modifyStatus === '20')) {
      tableData = tableData.filter(item => item?.productStatus !== 'N');
    }
    tableData = tableData.filter(item => item.stockCode.indexOf(filterProductName) > -1 || item.shortDesc.indexOf(filterProductName) > -1 || item.stockDesc.indexOf(filterProductName) > -1);
    return tableData
  }

  handleProductQuery = () => {
    const { productName } = this.state;
    this.setState({ filterProductName: productName !== undefined ? productName : '' })
  }

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    React.$stopPropagation(e);
  }

  // 还原修改
  handleCancelModify = () => {
    let { copyRowData, licenceData } = this.state;
    let rowData = copyRowData;
    rowData.cancelModifyFlag = 'Y';
    let licenceArr = rowData?.licenceArr || [];
    let productTableData = rowData?.productArr || [];
    if (licenceArr && licenceArr.length > 0) { // 不存在则默认返回一个
      for (let i = 0; i < licenceArr.length; i++) {
        let currentKey = i + 1;
        let currentFormData = this.filterLicenceFormData(currentKey, licenceArr[i]?.licenceTypeID || '');
        let currentLicenceRowData = this.filterLicenceValues(licenceArr[i], 'add', currentKey);
        licenceData.push({
          key: currentKey,
          licenceID: licenceArr[i]?.licenceID || '',
          deleteFlag: licenceArr[i]?.deleteFlag || '',
          rowData: currentLicenceRowData, // 可不存
          title: licenceArr[i]?.licenceTypeDesc || '许可证',
          formData: currentFormData
        });
        rowData = { ...rowData, ...currentLicenceRowData };
        this.state['licenceFormData' + currentKey] = currentFormData;
      }
    }
    productTableData = productTableData.filter(item => item.productStatus !== 'I')
    for (let i = 0; i < productTableData.length; i++) {
      productTableData[i].productStatus = 'N';
    }
    this.setState({ rowData, licenceArr, productTableData: Util.addKeyValueToDataSource(productTableData) }, () => {
      for (let i = 0; i < licenceData.length; i++) {
        if (licenceData[i]?.deleteFlag !== 'Y') {
          this.setColumnsLinkUrl(('licenceFormData' + licenceData[i].key), {});
        }
      }
      this.setColumnsLinkUrl('formData', {});
      this.setColumnsLinkUrl('addressFormData', {});
      this.setColumnsLinkUrl('otherFormData', {});
    });
  }

  render() {
    const { selectData, page, loading, tableData, total, totalWidth, columns, tabActive, rowData, formData, saveLoading, queryParams, rowID, productName, productLoading, productTotalWidth,
      productColumns, userInfo, userLoading, userTableData, userTotalWidth, userColumns, modalFormData, modalRowData, queryHeight, categoryData, addressFormData, otherFormData, licenceData, tabList, detailLoading, changeFlag
    } = this.state;
    const operationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span className="span" onClick={(e) => this.handleAuditRecord(record, e)}>
          {record?.tip === 'Y' ? (
            <Badge dot>
              审核记录
            </Badge>
          ) : '审核记录'}
        </span>
      ),
    };

    // 首营产品目录
    const productOperationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      fixed: 'right',
      className: 'sm-operation',
      render: (text, record, index) => (
        <span>
          {record?.productStatus !== 'D' ? (
            <Popconfirm
              placement="topRight"
              title="删除不可恢复，你确定要删除吗?"
              onCancel={this.handlePopconfirm}
              onClick={this.handlePopconfirm}
              onConfirm={(e) => this.handleProductDelete(record, index, e)}
            >
              <Icon type="delete" className="common-record-delete-span"></Icon>
              <span className="span common-record-delete-span">删除</span>
            </Popconfirm>
          ) : (
            categoryData?.revertFlag !== 'N' ? (
              <span className="span" onClick={(e) => this.handleProductDelete(record, index, e, 'revert')}>
                还原
              </span>
            ) : (
              <span style={{ cursor: 'no-drop' }}>
                <Icon type="delete" />
                删除
              </span>
            )
          )}
        </span>
      ),
    };

    // 供应商用户
    const userOperationObj = {
      width: 80,
      title: '操作',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span>
          {record && record.vendorLinkUserID ? (
            <>
              <Icon type="delete" className="common-record-delete-span"></Icon>
              <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleUserDelete(record)} >
                <span className="span common-record-delete-span">删除</span>
              </Popconfirm>
            </>
          ) : (
            <>
              <span className="span" onClick={(e) => this.handleSaveUser(record, e)}>保存</span>
            </>
          )}
        </span>
      ),
    };

    return (
      <div className="supplier-maintenance">
        <Row className="table-body-height">
          <Col span={10} className="sm-left-col">
            <div style={{ paddingRight: '8px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    {categoryData?.interfaceType === 'reviewed' ? '供应商单据审核' : '供应商列表'}
                  </div>
                )}
                extra={(
                  categoryData?.interfaceType === 'reviewed' ? '' : <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅显示启用</Checkbox>
                )}
              >
                <div ref={this.queryRef}>
                  <div className="flex-align-items">
                    {categoryData?.interfaceType === 'reviewed' ? (
                      <>
                        <div className="flex-align-items" style={{ marginRight: '15px' }}>
                          <span className="common-input-label">日期：</span>
                          <RangeDatePicker
                            width="300px"
                            format="YYYY-MM-DD"
                            isChange={true}
                            endDate={queryParams?.endDate || undefined}
                            startDate={queryParams?.startDate || undefined}
                            endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
                            startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
                          />
                        </div>
                      </>
                    ) : ''}
                    <span className="common-input-label">供应商：</span>
                    <Input
                      value={queryParams?.inputDesc || undefined}
                      style={{ width: categoryData?.interfaceType === 'reviewed' ? '150px' : '250px' }}
                      placeholder="输入代码/名称查询"
                      className="common-query-input"
                      onChange={(e) => this.handleModifyInputValue(e.target.value, 'inputDesc')}
                      onPressEnter={this.handleQuery}
                    />
                    <Button type="primary" onClick={this.handleQuery}>查询</Button>
                  </div>
                  <div style={{ marginTop: '12px', display: categoryData?.interfaceType === 'reviewed' ? 'block' : 'none' }}>
                    <span className="common-input-label">审核类型：</span>
                    <Radio.Group value={queryParams?.statusType} onChange={(e) => this.handleModifyInputValue(e.target.value, 'statusType')}>
                      {selectData && 'statusType' in selectData && Array.isArray(selectData.statusType) && selectData.statusType.map((item, index) => {
                        return (
                          <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                        )
                      })}
                    </Radio.Group>
                  </div>
                  <div style={{ margin: '12px 0' }}>
                    <span className="common-input-label">审核状态：</span>
                    <Radio.Group value={queryParams?.status} onChange={e => this.handleModifyInputValue(e.target.value, 'status')}>
                      {selectData && 'status' in selectData && Array.isArray(selectData.status) && selectData.status.map((item, index) => {
                        return (
                          <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                        )
                      })}
                    </Radio.Group>
                  </div>
                </div>
                <PublicTablePagination
                  param={{
                    page,
                    total,
                    pageSize: '20',
                    loading: loading,
                    data: tableData, // 表格数据
                    x: totalWidth, // 表格的宽度
                    componentName: categoryData?.interfaceType === 'reviewed' ? 'SupplierMaintenanceAudit' : 'SupplierMaintenance',
                    y: store.getState().tableHeight.y + 75 - queryHeight,
                    height: store.getState().tableHeight.y + 125 - queryHeight + 'px',
                    columns: categoryData?.interfaceType === 'reviewed' ? columns : [...columns, operationObj], // 表头配置
                  }}
                  compilePage={this.compilePage}
                  getColumns={this.getTableColumns}
                  onClickRowPublic={this.handleRowClick}
                  setRowClassNamePublic={this.handleRowClassName}
                />
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={14} className="sm-right-col">
            <Card
              size="small"
              className="sm-card-tabs"
              bordered={false}
              tabList={tabList}
              activeTabKey={tabActive}
              bodyStyle={{ padding: 0, paddingTop: '12px' }}
              tabBarExtraContent={(
                tabActive === '1' && categoryData?.interfaceType === 'create' ? (
                  <Button
                    icon="plus"
                    size="small"
                    className="add-btn add-btn-nohover"
                    onClick={this.handleReset}
                  >
                    新增供应商
                  </Button>
                ) : ''
              )}
              onTabChange={this.handleTabsChange}
            >

              <Spin spinning={detailLoading} tip="数据加载中……">
                <div style={{ height: store.getState().tableHeight.y + 186 + 'px', padding: '0 6px 56px 12px' }}>
                  <div className="scroll-bar-style" style={{ paddingRight: '6px', height: '100%', overflow: 'auto', display: tabActive === '1' ? 'block' : 'none' }}>
                    <Card
                      type="inner"
                      size="small"
                      title="营业执照"
                      bordered={false}
                      bodyStyle={{ paddingBottom: 0 }}
                      extra={(
                        categoryData?.entrySequenceBtnFlag === 'Y' ? (
                          <Button
                            size="small"
                            onClick={() => this.handleEntrySequence('SupplierMaintenance')}
                          >
                            录入顺序
                          </Button>
                        ) : ''
                      )}
                    >
                      <DynamicRenderingForm
                        isEnterJump='Y'
                        rowData={rowData}
                        formData={formData}
                        selectData={selectData}
                        handleQueryFormData={this.getTableColumns}
                        onRef={ref => this.baseInfoRef = ref}
                      />
                    </Card>
                    <Card
                      type="inner"
                      size="small"
                      title="许可证"
                      bordered={false}
                      bodyStyle={{ padding: '6px 0' }}
                      extra={(
                        <>
                          {categoryData?.interfaceType === 'create' && rowData?.auditStatus !== '20' && rowData?.modifyStatus !== '20' ? (
                            <Button
                              icon="plus"
                              size="small"
                              type="link"
                              onClick={this.handleLicenceAdd}
                            >
                              新增许可证
                            </Button>
                          ) : ''}
                          {categoryData?.entrySequenceBtnFlag === 'Y' ? (
                            <Button
                              size="small"
                              style={{ marginLeft: '12px' }}
                              onClick={() => this.handleEntrySequence('SupplierMaintenanceLicence')}
                            >
                              录入顺序
                            </Button>
                          ) : ''}
                        </>
                      )}
                    >
                      {licenceData && Array.isArray(licenceData) && licenceData.map((item, index) => {
                        return (
                          <div
                            key={index}
                            className="sm-licence-item"
                            style={{
                              borderBottom: licenceData.length === 1 || (licenceData.length > 1 && index === licenceData.length - 1) ? '' : '1px solid #e8e8e8',
                              paddingTop: licenceData.length === 1 ? '12px' : 0,
                              background: item?.deleteFlag === 'Y' ? '#f3f3f352' : !(item?.licenceID) ? '#f5fffc63' : '#fff'
                            }}
                          >
                            <div style={{ display: licenceData && licenceData.length > 1 ? 'flex' : 'none' }} className="flex-between-center">
                              <div className="card-title-left-icon sm-card-title">
                                <div></div>
                                <div>
                                  <span style={{ textDecoration: item?.deleteFlag === 'Y' ? 'line-through' : '' }}>
                                    {item?.title || ('许可证' + (item?.key || (index + 1)))}
                                  </span>
                                  {rowData?.auditStatus !== '30' ? '' : (item?.deleteFlag === 'Y' ? <span className="common-record-delete-span">【本次删除】</span> : (!(item?.licenceID) ? <span style={{ color: '#19cf9e' }}>【本次添加】</span> : ''))}
                                </div>
                              </div>
                              {index === 0 || categoryData?.interfaceType === 'reviewed' || rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? '' : (
                                item?.deleteFlag === 'Y' ? (
                                  categoryData?.revertFlag !== 'N' ? (
                                    <span className="span" onClick={() => this.handleLicenceDelete(index, item, 'revert')}>
                                      还原
                                    </span>
                                  ) : ''
                                ) : (
                                  <Popconfirm placement="topRight" title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleLicenceDelete(index, item)}>
                                    <span className="span common-record-delete-span">
                                      <Icon type="delete" style={{ marginRigth: '2px' }} />
                                      删除
                                    </span>
                                  </Popconfirm>
                                )
                              )}
                            </div>
                            <DynamicRenderingForm
                              isEnterJump='Y'
                              rowData={rowData}
                              formData={this.state['licenceFormData' + item.key] || []}
                              selectData={selectData}
                              handleQueryFormData={this.getLicenceTableColumns}
                              onRef={ref => this['licenceRef' + item.key] = ref}
                            />
                          </div>
                        )
                      })}
                    </Card>
                    <Card
                      type="inner"
                      size="small"
                      title="地址信息"
                      bordered={false}
                      bodyStyle={{ paddingBottom: 0 }}
                      extra={(
                        categoryData?.entrySequenceBtnFlag === 'Y' ? (
                          <Button
                            size="small"
                            onClick={() => this.handleEntrySequence('SupplierMaintenanceAddress')}
                          >
                            录入顺序
                          </Button>
                        ) : ''
                      )}
                    >
                      <DynamicRenderingForm
                        isEnterJump='Y'
                        rowData={rowData}
                        formData={addressFormData}
                        selectData={selectData}
                        handleQueryFormData={this.getAddressTableColumns}
                        onRef={ref => this.addressRef = ref}
                      />
                    </Card>
                    <Card
                      type="inner"
                      size="small"
                      title="其他信息"
                      bordered={false}
                      bodyStyle={{ paddingBottom: 0 }}
                      extra={(
                        categoryData?.entrySequenceBtnFlag === 'Y' ? (
                          <Button
                            size="small"
                            onClick={() => this.handleEntrySequence('SupplierMaintenanceOther')}
                          >
                            录入顺序
                          </Button>
                        ) : ''
                      )}
                    >
                      <DynamicRenderingForm
                        isEnterJump='Y'
                        rowData={rowData}
                        formData={otherFormData}
                        selectData={selectData}
                        handleQueryFormData={this.getOtherTableColumns}
                        onRef={ref => this.otherRef = ref}
                      />
                    </Card>
                  </div>
                  <div style={{ paddingRight: '6px', height: '100%', overflow: 'auto', display: tabActive === '2' ? 'block' : 'none' }}  >
                    <div className="flex-between-center" style={{ marginBottom: '12px' }}>
                      <div className="flex-align-items">
                        产品信息：<Input
                          placeholder="输入代码/名称/描述查询"
                          className="common-query-input"
                          style={{ width: '250px' }}
                          value={productName}
                          onChange={Util.commonInputChange.bind(this, 'productName')}
                          onPressEnter={this.handleProductQuery}
                        />
                        <Button type="primary" onClick={this.handleProductQuery}>查询</Button>
                      </div>
                      {categoryData?.supplierFlag === 'Y' || categoryData?.interfaceType === 'reviewed' || rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? (
                        <div className="flex-align-items">
                          <span style={{ display: 'inline-block', width: '16px', height: '16px', marginRight: '6px', background: '#b9eddf', borderRadius: '2px' }}></span>本次新增
                          <Checkbox style={{ marginLeft: '24px' }} checked={changeFlag} onChange={(e) => this.setState({ changeFlag: e.target.checked })}>仅查看变化</Checkbox>
                        </div>
                      ) : (
                        <Button
                          icon="plus"
                          className="add-btn add-btn-nohover"
                          onClick={this.handleProductAdd}
                        >新增产品</Button>
                      )}
                    </div>
                    <div style={{ height: store.getState().tableHeight.y + 84 + 'px' }}>
                      <PublicTablePagination
                        param={{
                          loading: productLoading,
                          data: this.filteProductTableData(), // 表格数据
                          x: productTotalWidth, // 表格的宽度
                          componentName: 'SelectFromBrandLibrary',
                          y: store.getState().tableHeight.y + 34,
                          height: store.getState().tableHeight.y + 84 + 'px',
                          columns: productColumns && productColumns.length > 0 ? (categoryData?.interfaceType === 'reviewed' || rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? productColumns : [...productColumns, productOperationObj]) : [], // 表头配置
                        }}
                        getColumns={this.getProductTableColumns}
                        onClickRowPublic={this.handleProductRowClick}
                        setRowClassNamePublic={this.handleProductRowClassName}
                      />
                    </div>
                  </div>
                  <div style={{ paddingRight: '6px', height: '100%', overflow: 'auto', display: tabActive === '3' && categoryData?.interfaceType === 'create' ? 'block' : 'none' }}  >
                    <div style={{ marginBottom: '12px' }}>
                      用户信息：<Input
                        placeholder="输入用户名/工号查询"
                        className="common-query-input"
                        style={{ width: '250px' }}
                        value={userInfo}
                        onChange={Util.commonInputChange.bind(this, 'userInfo')}
                        onPressEnter={this.getUserTableData}
                      />
                      <Button type="primary" onClick={this.getUserTableData}>查询</Button>
                      {categoryData?.interfaceType === 'reviewed' ? '' : (
                        <Button
                          icon="plus"
                          style={{ float: 'right' }}
                          className="add-btn add-btn-nohover"
                          onClick={this.handleUserAdd}
                        >新增用户</Button>
                      )}
                    </div>
                    <div style={{ height: store.getState().tableHeight.y + 84 + 'px' }}>
                      <PublicTablePagination
                        param={{
                          loading: userLoading,
                          data: userTableData, // 表格数据
                          x: userTotalWidth, // 表格的宽度
                          componentName: 'SupplierMaintenanceUser',
                          y: store.getState().tableHeight.y + 34,
                          height: store.getState().tableHeight.y + 84 + 'px',
                          columns: userColumns && userColumns.length > 0 ? [...userColumns, userOperationObj] : [], // 表头配置
                        }}
                        getColumns={this.getUserTableColumns}
                      // onClickRowPublic={this.handleUserRowClick}
                      // setRowClassNamePublic={this.handleUserRowClassName}
                      />
                    </div>
                  </div>
                </div>
              </Spin>
            </Card>
            <div className="sm-base-info-footer" style={{ display: tabActive === '3' ? 'none' : 'block' }}>
              {categoryData?.interfaceType === 'reviewed' ? ( // 审核
                <>
                  {rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? (
                    <Popconfirm
                      title="确定要退回吗?"
                      onConfirm={this.handleReturn}
                    >
                      <Button
                        ghost
                        type="danger"
                      >
                        审核不通过
                      </Button>
                    </Popconfirm>
                  ) : (
                    <Button
                      type="danger"
                      disabled
                    >
                      审核不通过
                    </Button>
                  )}
                  <Button
                    type="primary"
                    loading={saveLoading}
                    style={{ marginLeft: '12px' }}
                    disabled={!(rowData?.auditStatus === '20' || rowData?.modifyStatus === '20')}
                    onClick={() => this.handleModifyDataStatus('30')}
                  >
                    {saveLoading ? '审核中…' : '审核通过'}
                  </Button>
                </>
              ) : (
                <>
                  {/* {rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? (
                    <Popconfirm
                      title="撤回后不可恢复，确定要撤回吗?"
                      onConfirm={() => this.handleModifyDataStatus('10')}
                    >
                      <Button
                        ghost
                        type="danger"
                      >
                        撤销修改
                      </Button>
                    </Popconfirm>
                  ) : ( */}
                  {categoryData?.interfaceType === 'create' && rowData?.auditStatus === '30' && rowData?.modifyStatus === '25' ? (
                    rowData?.cancelModifyFlag === 'Y' ? (
                      <Button
                        ghost
                        type="danger"
                        disabled
                        style={{ marginRight: '12px' }}
                      >
                        放弃变更
                      </Button>
                    ) : (
                      <Popconfirm
                        title="放弃变更后不可恢复，确定要放弃吗?"
                        onConfirm={this.handleCancelModify}
                      >
                        <Button
                          ghost
                          type="danger"
                          style={{ marginRight: '12px' }}
                        >
                          放弃变更
                        </Button>
                      </Popconfirm>
                    )
                  ) : ''}
                  <Button
                    type="primary"
                    loading={saveLoading}
                    disabled={!(!rowID || rowData?.auditStatus === '' || rowData?.auditStatus === '10' || rowData?.auditStatus === '25' || (rowData?.auditStatus === '30' && (rowData?.modifyStatus === '10' || rowData?.modifyStatus === '25' || rowData?.modifyStatus === '30')))}
                    onClick={rowData?.auditStatus !== '30' ? () => this.handleSave(this.handleBaseInfoSave, '20') : () => this.handleSave(this.handleModifyDataStatus, '20')}
                  >
                    {saveLoading ? '提交中…' : ((rowData?.auditStatus === '25' || rowData?.modifyStatus === '25') && rowData?.cancelModifyFlag !== 'Y' ? '重新提交' : (rowData?.auditStatus === '30' ? '提交修改' : '提交审核'))}
                  </Button>
                </>
              )}
            </div>
          </Col>
        </Row>

        {/* 从产品库选择 */}
        <SelectFromBrandLibrary onRef={ref => this.brandLibraryRef = ref} addProductData={this.handleAddProductData} />

        {/* 审核记录 */}
        <SupplierAuditRecord
          auditTableCode="17060089"
          detailCode="17060090"
          propsRowIDIndex="vendorID"
          statusFlagIndex="productStatus"
          rowIDDataIndex="optVendorRecordID"
          interfaceType="SupplierMaintenance"
          detailTableDataIndex="proudctArr"
          tabList={[{
            key: '1',
            tab: '基本信息',
          }, {
            key: '2',
            tab: '首营产品目录',
          }]}
          totalWidth={productTotalWidth} // 表格的宽度
          columns={productColumns}
          onRef={ref => this.auditRecordRef = ref}
        />

        {/* 首映产品目录信息修改 */}
        <PublicModalFormHooks
          idField="stockID"
          onRef={ref => this.modalRef = ref}
          formData={modalFormData}
          rowData={modalRowData}
          selectData={selectData}
          recordFormInput={this.recordFormInput}
          handleSave={this.handleModalSave}
        />

        {/* 退回订单 */}
        <ReturnOrder modalTitle="退回" selectData={{}} modifyApplicationFormStatus={this.handleModifyDataStatus} onRef={ref => this.returnOrderRef = ref} />
      </div >
    )
  }
};

export default SupplierMaintenance;